import { t } from '@src/locales';
// components
import AddName from './components/addName'
import Chart from './components/chart'
import TaskSearchPanel from './components/taskSearchPanel'
import NoDataViewNew from '@src/component/common/NoDataViewNew';

// data
import {SEARCHDATA, FIXEDFIELDS} from './searchData'

/* Api */
import * as TaskApi from '@src/api/TaskApi.ts';
import * as CustomerApi from '@src/api/CustomerApi.ts';
import * as ReportApi from '@src/api/ReportApi.ts';

import {
  getProductFields
} from '@src/api/ProductApi';

import {
  CUSTOM_REPORT_GUIDE
} from '@src/component/guide/productV2Store'; // 引导存储
  
import { storageGet, storageSet } from '@src/util/storage'; // 存储方法

import { isOpenData } from '@src/util/platform';

// 回执表单过滤字段
const EXPORT_FILTER_FORM_TYPE = ['receiptAttachment', 'serviceIterm', 'systemAutograph', 'sparepart', 'attachment', 'address', 'autograph'];

export default {
  name: 'custom-report',
  data() {
    return {
      isOpenData,
      reportType: '', // 报表类型
      searchList: [], // 搜索数据
      reportName: {}, // 报表名称 
      chartName: '', // 选中的图表类型
      taskType: '', // 工单类型
      statisticType: '', // 统计指标
      statisticTypeList: [], // 统计指标列表
      taskTypeList: [], // 工单类型列表
      sorts: [], // 排序
      chartList: [], // 图表数据
      parasm: {}, // 条件
      chartTypeId: '', // 
      chartSatet: '',
      editType: '', // 判断是否编辑
      taskParams: {}, // 工单数据搜索条件
      taskView: {}, // 视图参数
      taskFrom: '', // 高级搜索初始化值
      chartType: [{name: t('common.base.table2'), icon: 'icon-detail-fill', id: 1}, {name: t('common.base.histogram'), icon: 'icon-signal-fill', id:2}, {name:t('common.base.lineChart'), icon: 'icon-fund-fill', id:3}, {name: t('common.base.pieChart'), icon: 'icon-piechart-circle-fil', id:4}],
      parentName: '', // 父节点名称
      grayFlag: false, // 灰度
    }
  },
  mounted() {

    let urlParams = {}
    window.location.href.split('?')[1].split('&').forEach(item => {
      urlParams[item.split('=')[0]] = item.split('=')[1]
    })

    this.reportType = urlParams.type
    this.editType = urlParams.edit
    this.parentName = urlParams.parentName;

    if (this.reportType !== 'produce') {
      this.$nextTick(() => {
        setTimeout(() => {
          this.guide()
        }, 500)
      })
    }

    if (this.reportType === 'produce' || urlParams.edit) {
      this.reportGet()
      this.taskTypes()
      this.getView()
    } else if (this.reportType === 'task') {
      this.taskTypes()
    } else if (this.reportType === 'product') {
      this.getProductFields()
    } else {
      this.getCustomerFields()
    }
   
    if (this.reportType !== 'produce') this.field()

    this.getGary();
  },
  methods:{
    // 获取灰度
    async getGary(){
      try{
        const res = await ReportApi.grayFunction();
        if(res.status !== 0) return;

        this.grayFlag = res.data.dashBoardAirp;
      }catch(err){
        console.log(err);
      }
    },
    // 选择图表
    checkChartType(v) {
      this.chartName = v.name; 
      this.chartTypeId = v.id;
      this.$nextTick(() => {
        if (this.$refs.chart) this.$refs.chart.stateText(this.statisticTypeList.filter(item => {return item.label === this.statisticType}))
      })
    },
    // 报表名称
    onSubmit(v) {
      this.reportName = v   
    },
    // 样式
    styles({icon}) {
      let sty;
      if (icon === 'icon-ditu2') {
        sty = 'task-bj9f'
      } else if (icon === 'icon-piechart-circle-fil') {
        sty = 'task-bjf7'
      } else if (icon === 'icon-detail-fill' || icon === 'icon-calendar-fill') {
        sty = 'task-bjc4'
      } else if (icon === 'icon-fund-fill') {
        sty = 'task-bjd1'
      } else {
        sty = 'task-bjc2'
      }
      return sty
    },
    /**
     * @description 获取工单字段列表
     * @return {Promise}
     */
    fetchTaskFields() {
      let params = {
        templateId: this.taskType,
        tableName: 'task',
      };
      return TaskApi.getTaskTemplateFields(params).then((result) => {
        result.forEach((field) => {
          field.group = 'task';
          field.label = field.displayName;
          field.field = field.fieldName;
        });
        return result;
      });
    },
    /**
     * @description 获取工单回执字段列表
     * @return {Promise}
     */
    fetchTaskReceiptFields() {
      let params = {
        templateId: this.taskType,
        tableName: 'task_receipt',
      };
      return TaskApi.getTaskTemplateFields(params).then((result) => {
        result.forEach((field) => {
          field.group = 'task_receipt';
          field.label = field.displayName;
          field.field = field.fieldName;
        });
        return result;
      });
    },
    // 工单高级搜索参数
    initialize() {
      Promise.all([this.fetchTaskFields(), this.fetchTaskReceiptFields()])
        .then((res) => {
          // 系统字段
          let sys = [...res[0], ...res[1]].filter(item => {
            return item.isSystem && EXPORT_FILTER_FORM_TYPE.indexOf(item.formType) === -1
          })
          // 自定义字段
          let cus = [...res[0], ...res[1]].filter(item => {
            return item.isSearch && !item.isSystem && EXPORT_FILTER_FORM_TYPE.indexOf(item.formType) === -1
          })
          this.seachSet([...sys, ...cus])
        })
        .catch((err) => {
          console.warn(err);
        });
    },
    // 客户高级搜索参数
    async getCustomerFields() {
      try {
        // 获取客户表单字段列表
        let result = await CustomerApi.getCustomerFields({isFromSetting: false});
        if (result.succ) {
          this.searchList = result.data.map(item => {return item});
        }
  
      } catch(err) {
        console.error('customer list get fields error', err);
      }
    },
    // S 产品高级搜索数据
    async getProductFields() {
    // 获取产品动态字段
      try {
        let res = await getProductFields({isFromSetting:false});
        this.productFields(res.data || [])
      } catch (error) {
        console.error('product-list fetch product fields error', error);
      }
    },
    productFields(dynamicFields) {

      let fixedFields = FIXEDFIELDS


      if (this.initData.productConfig.qrcodeEnabled) {
        fixedFields.push({
          displayName: this.$t('product.type.qrcodeId'),
          fieldName: 'qrcodeId',
          formType: 'text',
          isExport: false,
          isSystem: 1,
          placeholder: this.$t('product.placeholder.qrcodeId'),
          orderId: 10001
        })
      }
      let field = dynamicFields.filter(item => item.formType == 'customer')[0]
      if(field && field.setting.customerOption?.linkman) {
        fixedFields.push({
          displayName: this.$t('product.detail.catalogView.type.linkman'),
          fieldName: 'linkmanName',
          formType: 'text',
          isExport: true,
          isSystem: 0,
        })

        fixedFields.push({
          displayName: this.$t('common.base.phone'),
          fieldName: 'phone',
          isExport: true,
          isSystem: 0,
        })
      }

      if(field && field.setting.customerOption?.address) {
        fixedFields.push({
          displayName: this.$t('common.base.locationMap.address'),
          fieldName: 'address',
          isExport: true,
          formType: 'text',
          isSystem: 0,
        })
      }

      this.searchList = dynamicFields.concat(fixedFields)
        .filter(f => f.formType !== 'separator' && f.formType !== 'info' && f.formType !== 'autograph')
        .map(f => {

          // 调整字段顺序
          if (f.fieldName === 'name') {
            f.orderId = -13;
            f.show = true
          }

          if (f.fieldName === 'customer') {
            f.orderId = -12;
            f.show = true
          }

          if (f.fieldName === 'linkmanName') {
            f.orderId = -11;
            f.show = true
          }

          if (f.fieldName === 'phone') {
            f.orderId = -10;
            f.show = true
          }

          if (f.fieldName === 'address') {
            f.orderId = -9;
            f.show = true
          }

          if (f.fieldName === 'serialNumber') {
            f.orderId = -6;
            f.show = true
          }

          if (f.fieldName === 'type') {
            f.orderId = -5;
            f.show = true
          }

          if (f.fieldName === 'tags') {
            f.orderId = -8;
          }

          if (f.fieldName === 'productTemplate') {
            f.orderId = -7;
          }

          if (f.fieldName === 'remindCount') {
            f.orderId = -3;
          }

          if (f.fieldName === 'updateTime') {
            f.orderId = -2;
          }

          if (f.fieldName === 'createUser') {
            f.orderId = -1;
            f.show = true;
          }

          if (f.fieldName === 'createTime') {
            f.orderId = 0;
            f.show = true;
          }

          return f;
        })
        .sort((a, b) => a.orderId - b.orderId)
    },
    // E 产品高级搜索数据
    // 重置
    resetParams() {
      this.taskParams = {}
      this.taskView = {}
      this.taskFrom = ''
      this.$refs.TaskSearchPanel.hide()
      this.searchList = this.searchList.map(item => {return item})
      if (this.reportType === 'task' || this.chartSatet === 1) {
        this.aggregation()
      } else {
        this.$refs.TaskSearchPanel.clientCreate()
        this.customerCustomer()
      }
    },
    // 搜索条件
    seachSet(taskFields) {
      let linkman_list = [], address_list = [], product_list = []
      if (taskFields.length) {
        let first = taskFields.filter(item => {
          return item.displayName === this.$t('common.base.customer')
        })[0]
        if (first.setting.customerOption.linkman) {
          linkman_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'tlmName',
            displayName: this.$t('product.detail.catalogView.type.linkman'),
            exportAlias: 'customerLinkman',
            formType: 'select',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            show: true,
            guideProfessions: [],
            isGuideData: false,
            guideData: false,
          }]
        }
        if (first.setting.customerOption.address) {
          address_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'area',
            exportAlias: 'customerAddress',
            displayName: this.$t('common.base.locationMap.area'),
            formType: 'address',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          },
          {
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'cusAddress',
            displayName: this.$t('common.base.locationMap.detail'),
            formType: 'text',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          }]
        } 
        if (first.setting.customerOption.product) {
          product_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'product',
            displayName: this.$t('common.base.product'),
            formType: 'text',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          }]
        }
      }
      this.searchList = [...taskFields.filter(item => { return item.displayName !== this.$t('common.label.taskNo') && item.formType !== 'attachment'}).map(item => {if (item.fieldName === 'planTime'){item.isNull = 1} return item}), ...linkman_list, ...address_list, ...product_list, ...SEARCHDATA]
    },
    // 搜索
    advancedSearch() {
      const {params, dataView} = this.$refs.TaskSearchPanel.buildParams()
      this.$refs.TaskSearchPanel.hide()
      this.$refs.chart.clons()
      this.taskParams = params
      this.taskView = dataView
      if (this.reportType === 'task' || this.chartSatet === 1) {
        this.aggregation()
      } else {
        this.customerCustomer()
      }
    },

    // 创建视图
    async createView() {
      let params = {
        searchModel: Object.keys(this.taskView).length ? JSON.stringify(this.taskView) : '',
        type: this.reportType === 'task' || this.chartSatet === 1 ? 1 : 4
      }
      if (this.editType) params['customId'] = localStorage.getItem('customId')

      return this.editType ? await ReportApi.updateView(params) : await ReportApi.createView(params)
    },
    // 确认是否删除报表
    async delReport() {
      const confirm = await this.$platform.confirm(this.$t('report.customReportAggregate.pla4'))
      if (confirm) {
        this.reportDelete()
      }
    },
    // 引导
    guide() {
      if (storageGet(CUSTOM_REPORT_GUIDE) && storageGet(CUSTOM_REPORT_GUIDE) > 0){
        this.$Guide().destroy(CUSTOM_REPORT_GUIDE)
        return
      } 
      
      this.$Guide([{
        content:this.$t('report.customReportAggregate.title1'),
        haveStep: true,
        nowStep: 1,
        id: 'custom-report-guide',
        domId: 'custom-report-type',
        needCover: true,
        finishBtn: this.$t('common.base.ok'),
        lastFinish: true
      }, {
        content:this.$t('report.customReportAggregate.title2'),
        haveStep: true,
        nowStep: 2,
        id: 'custom-report-guide',
        domId: 'custom-report-condition',
        needCover: true,
        finishBtn: this.$t('common.base.ok'),
        lastFinish: true
      }, {
        content:this.$t('report.customReportAggregate.title3'),
        haveStep: true,
        nowStep: 3,
        id: 'custom-report-guide',
        domId: 'no-data-view-new',
        needCover: true,
        finishBtn: this.$t('common.base.ok'),
        lastFinish: true
      }, {
        content:this.$t('report.customReportAggregate.title4'),
        haveStep: true,
        nowStep: 4,
        id: 'custom-report-guide',
        domId: 'custom-report-submit',
        needCover: true,
        finishBtn: this.$t('common.base.ok'),
      }], 0, '', (e) => {
        return new Promise((resolve, reject) => {
          if (e.type === 'stop') this.chartName = ''
          resolve()
        })
      }).create().then(res_=>{if(res_){
        this.chartName = this.$t('common.base.histogram')
        storageSet(CUSTOM_REPORT_GUIDE, '1')
      }})    
    },
    // 工单类型
    async taskTypes() {
      this.taskTypeList = []
      const {succ, data} = await ReportApi.taskType()
      if (succ) {
        for(let key in data) {
          this.taskTypeList.push({
            value: key,
            label: data[key]
          })
        }
        this.taskTypeList.unshift({
          value: '',
          label: this.$t('common.base.all'),
        })
      }
    },
    // 获取统计指标
    async field(types = '') {
      let type, taskType = this.taskType
      switch (this.reportType) {
      case 'task':
        type = 1
        break;
      case 'client':
        type = 4
        break; 
      case 'product':
        type = 3
        break;    
      default:
        type = 2
        break;
      }

      const params = {
        type: types || type,
        taskType
      }
      const {success, result} = await ReportApi.field(params)
      if (success) {
        this.statisticTypeList = result
        this.chartList = []
        if (this.$refs.chart) this.$refs.chart.clons()
        if (this.statisticType) {
          this.$nextTick(() => {
            if (this.$refs.chart) this.$refs.chart.stateText(this.statisticTypeList.filter(item => {return item.label === this.statisticType}))
          })
        }
        if (this.reportType === 'task') {
          this.initialize()
        }
      }
    },
    // 筛选条件
    checkParam(v) {
      this.sorts = v
      if(!v.sorts) {
        delete this.sorts.sorts
      }
      if (this.reportType === 'task' || this.chartSatet === 1) {
        this.aggregation()
      } else {
        this.customerCustomer()
      }
    },
    // 工单搜索
    taskSearc() {
      this.statisticType = ''
      this.field()
    },
    // 统计指标
    statistic() {
      if (this.reportType === 'task' || this.chartSatet === 1) {
        this.aggregation()
      }
      else {
        this.customerCustomer()
      }    
      
      this.$nextTick(() => {
        if (this.$refs.chart) this.$refs.chart.stateText(this.statisticTypeList.filter(item => {return item.label === this.statisticType}))
      })
    },
    // 工单：根据关键字查询工单信息
    async aggregation() {

      const {taskType, statisticType, sorts, taskParams} = this
      if (!statisticType) {this.chartList = []; return}

      this.$loading.service()
      const params = {
        ...sorts,
        ...taskParams,
        templateId: taskType,
        aggregationStr: statisticType
      }
      this.parasm = params
      let res = await ReportApi.aggregation(params)
      this.$loading.service().close()
      if (res.success) {
        if (this.isOpenData && res.result) {
          if (window.WWOpenData?.initCanvas) {
            window.WWOpenData.initCanvas()
            window.WWOpenData.enableCanvasSharing()
          }
          let originItems = res.result || []
          let items = originItems.map(item => {
            return {
              type: 'userName',
              id: item.staffId
            }
          })
          
          const result = await new Promise((resolve, reject) => {
            window.WWOpenData.prefetch({ items }, (err, data) => {
              if (err) {
                return reject(err)
              }
              resolve(data)
            })
          })

          try {
            res.result = originItems.map((item, index) => {
              return Object.assign(item, { name: result.items[index].data })
            })
          } catch (error) {
            console.warn(error)
          }
        }
        this.chartList = res.result
      }
    },
    // 客户：根据关键字查询客户信息
    async customerCustomer() {

      const {statisticType, sorts, taskParams} = this
      if (!statisticType) {this.chartList = []; return}
      this.$loading.service()
      const params = {
        ...sorts,
        ...taskParams,
        aggregationStr: statisticType
      }
      this.parasm = params
      let res = await ReportApi.customerCustomer(params)
      this.$loading.service().close()
      if (res.success) {
        if (this.isOpenData && res.result) {
          if (window.WWOpenData?.initCanvas) {
            window.WWOpenData.initCanvas()
            window.WWOpenData.enableCanvasSharing()
          }
          let originItems = res.result || []
          let items = originItems.map(item => {
            return {
              type: 'userName',
              id: item.staffId
            }
          })
          
          const result = await new Promise((resolve, reject) => {
            window.WWOpenData.prefetch({ items }, (err, data) => {
              if (err) {
                return reject(err)
              }
              resolve(data)
            })
          })

          try {
            res.result = originItems.map((item, index) => {
              return Object.assign(item, { name: result.items[index].data })
            })
          } catch (error) {
            console.warn(error)
          }
        }
        this.chartList = res.result.map(item => {return item})
      }    
    },
    // 创建报表
    async reportCreate() {

      this.$loading.service()
      const res = await this.createView()
      
      const {reportName, reportType, chartTypeId, taskType, statisticType, sorts, taskParams} = this
      let sort = sorts ? sorts : {}

      let params = {
        type: reportType === 'task' ? 1 : 4,
        chartName: reportName.name,
        chartDesc: reportName.textarea,
        aggregationStr: statisticType,
        viewId: res.result,
        chartType: chartTypeId,
        taskType,
        searchModel: JSON.stringify(taskParams),
        ...sort
      }
      if (this.editType) params['customId'] = localStorage.getItem('customId')

      const {message, success, result} = this.editType ? await ReportApi.reportUpdate(params) : await ReportApi.reportCreate(params)
      
      // 过滤编辑 + 灰度
      if(this.grayFlag){
      try{
        if(result){
          const customeId = localStorage.getItem('customId');
          const reportThemeData = await ReportApi.insertReportTheme({
            parentName: decodeURI(this.parentName),
            reportName: reportName.name,
            customId: this.editType ? customeId : result,
            reportIcon: chartTypeId,
            textArea: reportName.textarea
          })
        }
      }catch(err){
        console.log('ReportApi.insertReportTheme', err);
      }
      }

      this.$loading.service().close()
      this.$platform.alert(message)
      
      if (!success) return
      window.parent.flashSomePage([{
        type: 'M_DASHBOARD_TJBB',
      }]);

      if (!this.editType) localStorage.setItem('customId', result)

      if(this.grayFlag){
        window.location.href = `${this.$resourcePrefix}/stats/customReport?type=produce&parentName=${this.parentName}`;
      }else {
        window.location.href = `${this.$resourcePrefix}/stats/customReport?type=produce`;
      }
    },
    // 获取指定的的自定义报表
    async reportGet() {
      const params = {
        customId: localStorage.getItem('customId')
      }
      const {result} = await ReportApi.reportGet(params)

      this.reportName = {
        name: result.chartName,
        textarea: result.chartDesc
      }
      
      this.statisticType = result.aggregationStr
      this.taskType = result.taskType
      this.sorts = result.sortJson ? JSON.parse(result.sortJson) : ''
      this.chartSatet = result.type
      this.chartTypeId = result.chartType
      this.taskParams = JSON.parse(result.searchModel)

      switch (result.chartType) {
      case 1:
        this.chartName = this.$$t('common.base.table2')
        break;
      case 2:
        this.chartName = this.$t('common.base.histogram')
        break; 
      case 3:
        this.chartName = this.$t('common.base.lineChart')
        break;     
      default:
        this.chartName = this.$t('common.base.pieChart')
        break;
      }
      // 因为此方法里里面有置空数据的操作 移动到前面来 防止数据为空   
      await this.field(result.type).catch(err => console.error('【fetch field(统计指标) failed】:', err))
      
      // type 1工单、2事件、3产品、4客户报表
      if (result.type == 4) {
        this.getCustomerFields()
        this.customerCustomer()
      } else if (result.type === 1) {
        this.initialize()
        this.aggregation()
      }

    },
    // 获取自定义视图
    async getView() {

      const params = {
        customId: localStorage.getItem('customId')
      }
      const {result} = await ReportApi.getView(params)
      this.taskFrom = JSON.parse(result.searchModel || '{}')
      this.taskView = JSON.parse(result.searchModel || '{}')
    },
    // 删除报表
    async reportDelete() {
      const params = {
        customId: localStorage.getItem('customId')
      }
      const {message, result} = await ReportApi.reportDelete(params)

      // 报表权限控制 + 灰度
      if(this.grayFlag){
      try {
        if(result){
          const customId = localStorage.getItem('customId');
          const delData = await ReportApi.deleteReportTheme(customId);
        }
      }catch(err){
        console.log('ReportApi.deleteReportTheme', err);
      }
      }

      this.$platform.alert(message);
      
      window.parent.flashSomePage([{
        type: 'M_DASHBOARD_TJBB',
      }]);

      let id = window.frameElement.dataset.id
      return this.$platform.closeTab(id)
    },
    // 编辑
    editChares() {
      let type = this.chartSatet === 1 ? 'task' : 'client'
      
      if(this.grayFlag){
        window.location.href = `${this.$resourcePrefix}/stats/customReport?type=${type}&edit=1&parentName=${this.parentName}`
      }else {
        window.location.href = `${this.$resourcePrefix}/stats/customReport?type=${type}&edit=1`;
      }
    }
  },
  components: {
    [AddName.name]: AddName,
    [Chart.name]: Chart,
    [NoDataViewNew.name]: NoDataViewNew,
    [TaskSearchPanel.name]: TaskSearchPanel
  }
}
